<?php
namespace app\admin\controller;

use app\common\component\user_vip\UserVipModel;
use app\common\component\user_wallet_silver\UserWalletSilverModel;

class UserWalletSilver extends ControllerBase {
	public function _initialize() {
		$this -> checkLogin();
	}

	public function index() {
		$userWalletSilvers = UserWalletSilverModel::alias('u_w_s')
			-> join('league_user u', 'u_w_s.user_id = u.user_id')
			-> field(
				'u_w_s.*, ' .
				'u.username, u.realname, u.phone, u.bank_code'
			)
			->order('u_w_s.status ASC') -> paginate(10);

		$this -> view -> assign('userWalletSilvers', $userWalletSilvers);

		return $this -> view -> fetch();
	}

	public function checkWithdraw() {
		$getUserWalletSilver = UserWalletSilverModel::get(['user_wallet_silver_id', $this -> request -> get('user_wallet_silver_id')]);
		if($getUserWalletSilver) {
			$getUserWalletSilver -> status = 9;
			$getUserWalletSilver -> remaining_time = 0;

			if($getUserWalletSilver -> save()) {
				echo '<meta charset="utf-8"><script>alert("审核成功!");window.location.href="/shuashuale/wallet/silver";</script>';exit;
			}
			echo '<meta charset="utf-8"><script>alert("审核失败!");window.location.href="/shuashuale/wallet/silver";</script>';exit;
		}

		echo '<meta charset="utf-8"><script>alert("银豆订单不存在!");window.history.go(-1);</script>';exit;
	}

	public function delete() {
		$getUserWalletSilver = UserWalletSilverModel::get(['user_wallet_silver_id', $this -> request -> get('user_wallet_silver_id')]);

		\think\Db::startTrans();
		try {
			if($getUserWalletSilver) {
				$getUserVip = UserVipModel::get(['user_id', $getUserWalletSilver -> from_user_id]);
				if($getUserVip) {
					if($getUserVip -> days >= getParam('USER_REGISTERS_GIVE_VIP')) {
						$getUserVip -> days -= getParam('USER_REGISTERS_GIVE_VIP');
					} else {
						$getUserVip -> days = 0;
					}
	
					if(!$getUserVip -> save()) {
						throw new \Exception('删除失败!');
					}
				}

				if(!$getUserWalletSilver -> delete()) {
					throw new \Exception('删除失败!');
				}
			}

			\think\Db::commit();
		} catch(\Exception $e) {
			\think\Db::rollback();
			echo '<meta charset="utf-8"><script>alert("' . $e -> getMessage() . '!");window.location.href="/shuashuale/wallet/silver";</script>';exit;
		}

		echo '<meta charset="utf-8"><script>alert("删除成功!");window.location.href="/shuashuale/wallet/silver";</script>';exit;
	}
}